package org.jeecg.modules.simulator.recorder;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.simulator.jsonot.BeforeFiveMinPeople;
import org.jeecg.modules.simulator.jsonot.OutputWriteFileObject;
import org.jeecg.modules.simulator.model.line.station.station.Station;

import org.jeecg.modules.simulator.model.train.event.TrainListener;
import org.jeecg.modules.simulator.recorder.event.OutputWriteFileEvent;
import org.jeecg.modules.simulator.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: simulator-b20240918
 * @description:
 * @author: renzhg
 * @create: 2024-11-19 16:18
 **/
@Component
@Slf4j
public class Reacorder {
    private static final Logger logger = LoggerFactory.getLogger(Reacorder.class);

//    @Setter
//    String sceneCode;

    public static final String COMMON_DIRECTORY = "D:/aaaaaa/stationjsonfile/";

    @EventListener
    public void recodeFile(OutputWriteFileEvent event) {
        OutputWriteFileObject outputWriteFile = (OutputWriteFileObject) event.getSource();
        String now =outputWriteFile.getNow();
        Map<String,List<BeforeFiveMinPeople>> bfmpMap=outputWriteFile.getBfmpMap();
        List<SectCurInfoVo>  sectCurInfoVoList=outputWriteFile.getSectCurInfoVoList();
        NetCurInfoVo netCurInfo=outputWriteFile.getNetCurInfo();
        List<LineCurInfoVo> lineCurInfoVoList=outputWriteFile.getLineCurInfoVoList();
//        List<TrainCurInfoVo> trainCurInfoVos=outputWriteFile.getTrainCurInfoVos();

        if(bfmpMap!=null&&bfmpMap.size()>0){
            writeOrAppendBeforeFiveMinPeopleToFile(bfmpMap);
        }

        if(sectCurInfoVoList!=null&&sectCurInfoVoList.size()>0){
            write2SectCurInfoVo(sectCurInfoVoList);
        }

        if(lineCurInfoVoList!=null&&lineCurInfoVoList.size()>0){
            writeNetCurInfo(netCurInfo,now);
        }
        if(lineCurInfoVoList!=null&&lineCurInfoVoList.size()>0){
            writeLineCurInfo(lineCurInfoVoList);
        }

    }





    public void writeLineCurInfo(List<LineCurInfoVo> lineCurInfoVoList) {
        ObjectMapper objectMapper = new ObjectMapper();


        for(int i=0;i<lineCurInfoVoList.size();i++){
            LineCurInfoVo lineCurInfoVo=lineCurInfoVoList.get(i);

            String fileName = lineCurInfoVo.getLineId()+ ".json"; // 获取文件名并添加 .json 后缀
            File jsonFile = new File(COMMON_DIRECTORY +"LineCurInfo/"+fileName);
            try{
                if (jsonFile.exists()) {
                    FileWriter fileWriter = new FileWriter(jsonFile, true); // 以追加模式打开文件
                    fileWriter.write(objectMapper.writeValueAsString(lineCurInfoVo) + System.lineSeparator());
                    fileWriter.close();
                    System.out.println("Successfully appended to file: " + jsonFile.getAbsolutePath());
                } else{
                    // 如果文件不存在，则创建新文件并写入内容
                    objectMapper.writeValue(jsonFile, lineCurInfoVo);
                    System.out.println("Successfully created file: " + jsonFile.getAbsolutePath());
                }
            }catch (Exception e) {
                e.printStackTrace();
                System.err.println("Failed to write to file: " + jsonFile.getAbsolutePath());
            }


        }


    }



    public void writeNetCurInfo(NetCurInfoVo netCurInfo,String now) {
        ObjectMapper objectMapper = new ObjectMapper();

        String fileName = "netInfor"+now.replace(":", "_")+ ".json"; // 获取文件名并添加 .json 后缀
        File jsonFile = new File(COMMON_DIRECTORY +"NetCurInfo/"+ fileName);
        try{
            if (jsonFile.exists()) {
                FileWriter fileWriter = new FileWriter(jsonFile, true); // 以追加模式打开文件
                fileWriter.write(objectMapper.writeValueAsString(netCurInfo) + System.lineSeparator());
                fileWriter.close();
                System.out.println("Successfully appended to file: " + jsonFile.getAbsolutePath());
            } else{
                // 如果文件不存在，则创建新文件并写入内容
                objectMapper.writeValue(jsonFile, netCurInfo);
                System.out.println("Successfully created file: " + jsonFile.getAbsolutePath());
            }
        }catch (Exception e) {
            e.printStackTrace();
            System.err.println("Failed to write to file: " + jsonFile.getAbsolutePath());
        }
    }



    public void write2SectCurInfoVo(List<SectCurInfoVo> sectCurInfoVoList) {
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();
        for(int i=0;i<sectCurInfoVoList.size();i++){
            SectCurInfoVo sectCurInfoVo=sectCurInfoVoList.get(i);
            String fileName = sectCurInfoVo.getSectName()+ ".json"; // 获取文件名并添加 .json 后缀
            File jsonFile = new File(COMMON_DIRECTORY +"SectCurInfo/"+ fileName);
            try{
                if (jsonFile.exists()) {
                    // 如果文件存在，则追加内容
                    FileWriter fileWriter = new FileWriter(jsonFile, true); // 以追加模式打开文件
                    fileWriter.write(objectMapper.writeValueAsString(sectCurInfoVo) + System.lineSeparator());
                    fileWriter.close();
                    System.out.println("Successfully appended to file: " + jsonFile.getAbsolutePath());
                } else{
                    // 如果文件不存在，则创建新文件并写入内容
                    objectMapper.writeValue(jsonFile, sectCurInfoVo);
                    System.out.println("Successfully created file: " + jsonFile.getAbsolutePath());
                }
            }catch (Exception e) {
                e.printStackTrace();
                System.err.println("Failed to write to file: " + jsonFile.getAbsolutePath());
            }

        }

    }

    public  void writeOrAppendBeforeFiveMinPeopleToFile(Map<String,List<BeforeFiveMinPeople>> bfmpMap) {

        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 遍历 map 的每个条目

        for(Map.Entry<String,List<BeforeFiveMinPeople>>  entry:bfmpMap.entrySet()){
            // 创建 JSON 文件，使用公共文件夹路径





            String fileName =  entry.getKey().replace(":", "_")+ ".json"; // 获取文件名并添加 .json 后缀
            File jsonFile = new File(COMMON_DIRECTORY +"BeforeFiveMin/"+ fileName);
            try {
                if (jsonFile.exists()) {
                    // 如果文件存在，则追加内容
                    FileWriter fileWriter = new FileWriter(jsonFile, true); // 以追加模式打开文件
                    fileWriter.write(objectMapper.writeValueAsString(entry.getValue()) + System.lineSeparator());
                    fileWriter.close();
                    System.out.println("Successfully appended to file: " + jsonFile.getAbsolutePath());
                } else {
                    // 如果文件不存在，则创建新文件并写入内容
                    objectMapper.writeValue(jsonFile, entry.getValue());
                    System.out.println("Successfully created file: " + jsonFile.getAbsolutePath());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("Failed to write to file: " + jsonFile.getAbsolutePath());
            }

        }


    }



    //    @Setter
//    @Getter
//    private Map<String, Station> stationInThisLineMap = new HashMap<>();
    //向本地银盘打印输出信息
    public void linePublishInfo(String now) {

//        StationInfoVo stationInfoVo = UnitCache.stationInfoVoMap.get(sceneCode);、


//        stationInThisLineMap.forEach((k, v) -> {
//            StationInstantInfo stationInstantInfo = new StationInstantInfo();
//            stationInstantInfo.setStationId(v.getId());
//            stationInstantInfo.setStationName(v.getName());
//            stationInstantInfo.setSceneCode(sceneCode);
//            stationInstantInfo.setTimePt(now);
//
//            if(v.getId().equals("1043")){
//                System.out.println("1043");
//            }
//            stationInstantInfo.setStationTotalAndInstantInputPersonNum(v.getStationInstantInfo().getStationInstantInputPersonNum()); //当前站点进站人数
//            stationInstantInfo.setStationTotalAndInstantOutPersonNum(v.getStationInstantInfo().getStationInstantOutPersonNum()); //当前站点出站人数
//            stationInstantInfo.setStationTotalAndInstantWalkPersonNum(v.getStationInstantInfo().getStationInstantWalkPersonNum()); //当前站点步行人数
//            stationInstantInfo.setStationTotalAndInstantWaitPersonNum(v.getStationInstantInfo().getStationInstantWaitPersonNum()); //当前站点等待人数
//            writeOrAppendStationInstantInfoToFile(v.getId(),  stationInstantInfo);



//            if(stationInfoVo.stationInstantInfoMap.containsKey(v.getId())){
//                stationInfoVo.stationInstantInfoMap.get(v.getId()).add(stationInstantInfo);
//            }else{
//                stationInfoVo.stationInstantInfoMap.put(v.getId(), new ArrayList<>());
//                stationInfoVo.stationInstantInfoMap.get(v.getId()).add(stationInstantInfo);
//            }



//        });
//        UnitCache.stationInfoVoMap.put(sceneCode, stationInfoVo);

    }


    public  void writeOrAppendStationInstantInfoToFile(String key, StationInstantInfo stationInstantInfo) {
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 遍历 map 的每个条目

        String fileName = key+ ".json"; // 获取文件名并添加 .json 后缀


        // 创建 JSON 文件，使用公共文件夹路径
        File jsonFile = new File(COMMON_DIRECTORY + fileName);

        try {
            if (jsonFile.exists()) {
                // 如果文件存在，则追加内容
                FileWriter fileWriter = new FileWriter(jsonFile, true); // 以追加模式打开文件
                fileWriter.write(objectMapper.writeValueAsString(stationInstantInfo) + System.lineSeparator());
                fileWriter.close();
                System.out.println("Successfully appended to file: " + jsonFile.getAbsolutePath());
            } else {
                // 如果文件不存在，则创建新文件并写入内容
                objectMapper.writeValue(jsonFile, stationInstantInfo);
                System.out.println("Successfully created file: " + jsonFile.getAbsolutePath());
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Failed to write to file: " + jsonFile.getAbsolutePath());
        }

    }




}
